<script lang="ts" setup>

import {ref, watch} from "vue";
import SiteNavigation from "../Component/SiteNavigation.vue";
import {Plus} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";

defineProps({
  enterAction: {
    type: Object,
    required: true
  }
});
let savedMode = window.utools.dbStorage.getItem("mode")
const mode = ref(savedMode !== null ? Number(savedMode) : 0)

// 监听变化并存储
watch(mode, (val) => {
  window.utools.dbStorage.setItem("mode", val)
})

const visible = ref(false)
const form = ref({
  name: '',
  url: '',
  iconUrl: ''
})
const formRef = ref()

const rules = {
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  url: [{ required: true, message: '地址不能为空', trigger: 'blur' }]
}

const map = new Map();
const url = ref('')
const urlList = ref([
  {
    name: '百度',
    url: 'www.baidu.com',
    iconUrl: ''
  },
  {
    name: '必应',
    url: 'www.bing.com',
    iconUrl: 'https://www.bing.com/sa/simg/favicon-trans-bg-blue-mg-png.png'
  },
  {
    name: 'bilibili',
    url: 'www.bilibili.com',
    iconUrl: ''
  },
  {
    name: '抖音',
    url: 'www.douyin.com',
    iconUrl: 'https://p-pc-weboff.byteimg.com/tos-cn-i-9r5gewecjs/favicon.png'
  }
])

if (window.utools.dbStorage.getItem('firstIn') === null) {
  window.utools.dbStorage.setItem('urlList', JSON.stringify(urlList.value))
  window.utools.dbStorage.setItem('firstIn', 'true')
}else {
  urlList.value = JSON.parse(window.utools.dbStorage.getItem('urlList'))
}

function handleConfirm() {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('表单数据：', form.value)
      ElMessage.success('提交成功')
      visible.value = false

      let listString = window.utools.dbStorage.getItem('urlList')
      let list = listString === null || listString === '' ? [] : JSON.parse(listString)
      list.push(form.value)
      window.utools.dbStorage.setItem('urlList', JSON.stringify(list))
      urlList.value = list
    }
  })
}
function skip(url:string) {
  let winName = Date.now().toString(36) + Math.random().toString(36).substring(2) + '-' + mode.value
  const [topText, bottomText] = window.utils.getRandomAdPair()
  const win = window.utools.createBrowserWindow(`skip-${mode.value}.html?url=${url}&winName=${winName}&topText=${topText}&bottomText=${bottomText}`, {
    width: 800,
    height: 600,
    frame: false,
    transparent: true,
    backgroundColor: '#00000000',
    webPreferences: {
      preload: 'preload/services.js',
      partition: 'persist:mywindow',
      webviewTag: true,
      nodeIntegration: false,
      contextIsolation: true
    }
  }, () => {
    map.set(winName,win)
    // 打开调试
    // win.webContents.openDevTools()
  });
}

function delUrl(index) {
  urlList.value.splice(index, 1)
  window.utools.dbStorage.setItem('urlList', JSON.stringify(urlList.value))
}

window.electron.on('mouseenter-in',(data) => {
  const win = map.get(data)
  // win.setSize(800,600)
})
window.electron.on('mouseenter-out',(data) => {
  const win = map.get(data)
  // win.setSize(100,100)
})
window.electron.on('minimize',(data) => {
  const win = map.get(data)
  win.minimize()
})
window.electron.on('win-sticky',(data) => {
  const win = map.get(data.winName)
  win.setAlwaysOnTop(data.isSticky)
})
window.electron.on('win-close',(data) => {
  map.delete(data)
})
window.messageBus.subscribe((message) => {
  if(message.type === 'closeAll') {
    map.forEach(win => win.close())
  }
  if(message.type === 'hide') {
    map.forEach((win, winName) => {
      const parts = winName.split('-');
      if (parts.length > 1 && parts[1] == '0') {
        win.webContents.send('hide',0)
        setTimeout(() => {
          win.minimize()
        },50)
      }else {
        win.minimize()
      }
    })
  }
  if(message.type === 'show') {
    map.forEach(win => {
      win.webContents.send('hide',100)
    })
  }
})
</script>

<template>
  <div class="home">
    <!-- 模式选择 -->
    <div class="mode-selector">
      <el-radio-group v-model="mode" size="small">
        <el-radio :label="0">模式 1</el-radio>
        <el-radio :label="1">模式 2</el-radio>
        <el-radio :label="2">模式 3</el-radio>
        <el-radio :label="3">模式 4</el-radio>
      </el-radio-group>
    </div>

    <!-- 搜索栏 -->
    <div class="search">
      <el-input
          style="width: 85%"
          id="value"
          type="text"
          v-model="url"
          @keyup.enter="skip(url)"
          placeholder="请输入网址..."
          autofocus
      />
    </div>

    <!-- 网站导航 -->
    <div class="site-navigation">
      <template v-for="(item,index) in urlList" :key="index">
        <SiteNavigation
            style="margin: 5px 5px 0 0"
            @delete="delUrl(index)"
            @click="skip(item.url)"
            :name="item.name"
            :url="item.url"
            :iconUrl="item.iconUrl"
        />
      </template>
      <el-card
          @click="visible = true"
          shadow="hover"
          style="display: flex;align-items: center;justify-content: center;margin-top: 5px"
      >
        <el-icon><Plus /></el-icon>
      </el-card>
    </div>
  </div>

  <el-dialog v-model="visible" title="添加信息" width="400px" :close-on-click-modal="false">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称" clearable />
      </el-form-item>
      <el-form-item label="地址" prop="url">
        <el-input v-model="form.url" placeholder="请输入地址" clearable />
      </el-form-item>
      <el-form-item label="图片地址">
        <el-input v-model="form.iconUrl" placeholder="请输入图片地址（可选）" clearable />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.home {
  display: flex;
  flex-direction: column;
}

.mode-selector {
  display: flex;
  justify-content: flex-end;
  width: 85%;              /* 和搜索框宽度保持一致 */
  margin: 0 auto;          /* 居中容器，保证右边对齐 */
  margin-top: 40px;        /* 与页面顶部/搜索框间距 */
  margin-bottom: -50px;    /* 往下压一点，接近搜索框 */
}

.mode-selector .el-radio {
  margin-right: 8px;       /* 单选框之间间隔 */
}

.search {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 75px;
}

.site-navigation {
  display: flex;
  margin-top: 25px;
  flex-wrap: wrap;
  margin-left: 60px;
  margin-right: 60px;
}

.card {
  display: flex;
  margin-top: 2px;
}
</style>
